﻿using HQHS.Library.DAL.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace HQHS.Library.DAL
{
    public class GOTSqlConnectionManager : IConnectionManager, IDisposable
    {
        private SqlConnection conn = null;
        private SqlTransaction tran = null;
        private readonly ConnectionStringSettings csSetting;
        private bool _isInTransaction = false;
        private bool _disposedValue = false;

        #region Constructors
        public GOTSqlConnectionManager()
        {
            csSetting = ConfigurationManager.ConnectionStrings["ConnectionString"];
        }
        public GOTSqlConnectionManager(string name, string connString)
        {
            csSetting = new ConnectionStringSettings(name, connString, "System.Data.SqlClient");
        }
        #endregion

        #region Public Properties
        public bool IsInTransaction { get { return _isInTransaction; } }
        public bool IsOpen
        {
            get
            {
                if (conn != null && conn.State != ConnectionState.Closed)
                {
                    return true;
                }

                return false;
            }
        }
        #endregion

        #region Public Methods
        public SqlDataReader ExecuteReader(ICommand command)
        {
            return (SqlDataReader)this.CommandExcuteFactory(command.SqlCommand, CommandExecuteTypes.DataReader);
        }
        public object ExecuteNonQuery(ICommand cmd)
        {
            return this.CommandExcuteFactory(cmd.SqlCommand, CommandExecuteTypes.NonQuery);
        }
        #endregion

        #region  IConnectionManager Implementation
        public void BeginTransaction()
        {
            if (!this._isInTransaction)
            {
                this._isInTransaction = true;
                if (this.conn == null)
                {
                    this.conn = new SqlConnection(this.csSetting.ConnectionString);
                }
                if (this.conn.State != ConnectionState.Open) this.conn.Open();
                this.tran = this.conn.BeginTransaction();
            }
            else
            {
                throw new Exception("Transaction already exists.");
            }
        }
        public void Commit()
        {
            if (this.tran != null)
            {
                this.tran.Commit();
                this.tran = null;
            }
            this._isInTransaction = false;
        }
        public void Rollback()
        {
            if (this.tran != null)
            {
                this.tran.Rollback();
                this.tran = null;
            }
            this._isInTransaction = false;
        }
        public void Close()
        {
            if (_isInTransaction)
            {
                throw new InvalidOperationException("Cannot close connection because a transaction is still open.");
            }
            if (this.conn != null) this.conn.Close();
            this._isInTransaction = false;
        }
        #endregion

        #region  IDisposable Implementation
        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        protected void Dispose(bool disposing)
        {
            if (_disposedValue == false)
            {
                if (disposing)
                {
                    if (this.tran != null)
                    {
                        this.tran.Dispose();
                        this.tran = null;
                    }
                    if (this.conn != null)
                    {
                        this.conn.Dispose();
                        this.conn = null;
                    }
                }

                // Free shared unmanaged resources

            }
            _disposedValue = true;
        }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            // Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
            this.Dispose(true);
            GC.SuppressFinalize(this);
        }
        #endregion

        #region Private Methods
        private object CommandExcuteFactory(SqlCommand command, CommandExecuteTypes type)
        {
            try
            {
                object result = null;
                this.SetConnection();
                command.Connection = this.conn;
                command.Transaction = this.tran;

                switch (type)
                {
                    case CommandExecuteTypes.DataReader:
                        result = command.ExecuteReader();
                        break;
                    case CommandExecuteTypes.NonQuery:
                        result = command.ExecuteNonQuery();
                        break;
                    case CommandExecuteTypes.Scalar:
                        result = command.ExecuteScalar();
                        break;
                    default:
                        throw new Exception("Unknown command type.");
                }

                return result;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void SetConnection()
        {
            if (this.conn == null)
            {
                this.conn = new SqlConnection(this.csSetting.ConnectionString);
            }
            if (this.conn.State != ConnectionState.Open) this.conn.Open();
            if (this._isInTransaction == true && this.tran == null)
            {
                this.tran = this.conn.BeginTransaction();
            }
        }
        private enum CommandExecuteTypes
        {
            NonQuery = 1,
            Scalar = 2,
            DataReader = 3
        }
        #endregion
    }
}
